package com.zuimei.zuimei.http;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.zuimei.zuimei.utils.LocalCacheUtil;
import com.zuimei.zuimei.utils.MemoryCacheUtil;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络帮助类
 */

public class HttpHelper {
    private Context mContext;
    private Handler mHandler = new Handler();
    private MemoryCacheUtil mMemoryCacheUtil;
    private LocalCacheUtil mLocalCacheUtil;
    private OnLoadCompletedListener mListener;

    public HttpHelper(Context context) {
        mContext = context;
    }

    public interface OnLoadCompletedListener {
        void onSuccess(String result);

        void onFailure();
    }

    /**
     * 获取数据
     */
    public void getData(String url, OnLoadCompletedListener listener) {
        mListener = listener;
        // 先从本地缓存中读取数据,如果有,就直接返回,如果没有,才从网络加载
        String result = getCache(url);
        if (result != null) {
            if (mListener != null) {
                mListener.onSuccess(result);
            }
        } else {
            getDataFromNet(url, mListener);
        }
    }

    /**
     * 刷新数据
     */
    public void getRefreshData(String url, OnLoadCompletedListener listener) {
        mListener = listener;
        getDataFromNet(url, mListener);
    }

    /**
     * 获取缓存
     */
    private String getCache(String url) {
        //先从内存里找数据
        mMemoryCacheUtil = new MemoryCacheUtil();
        //内存找数据
        String jsonStringFromMemory = mMemoryCacheUtil.getJsonStringFromMemory(url);
        if (!TextUtils.isEmpty(jsonStringFromMemory)) {
            Log.d("TAG", "----内存缓存");
            return jsonStringFromMemory;
        } else {
            //本地找数据
            mLocalCacheUtil = new LocalCacheUtil(mContext);
            String jsonStringFromLocal = mLocalCacheUtil.getJsonStringFromLocal(url);
            if (!TextUtils.isEmpty(jsonStringFromLocal)) {
                Log.d("TAG", "----本地缓存");
                //设置内存缓存
                mMemoryCacheUtil.setJsonStringToMemory(url, jsonStringFromLocal);
                return jsonStringFromLocal;
            } else {
                return null;
            }
        }
    }

    /**
     * 从网络中获取数据
     */
    private void getDataFromNet(final String url, OnLoadCompletedListener listener) {
        mListener = listener;
        mMemoryCacheUtil = new MemoryCacheUtil();
        mLocalCacheUtil = new LocalCacheUtil(mContext);
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (mListener != null) {
                                    mListener.onFailure();
                                }
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, final Response response) throws
                            IOException {

                        final String result = response.body().string();
                        //设置缓存
                        mMemoryCacheUtil.setJsonStringToMemory(url, result);
                        mLocalCacheUtil.setJsonStringToLocal(url, result);
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (mListener != null) {
                                    mListener.onSuccess(result);
                                }
                            }
                        });
                    }
                });
            }
        }).start();
    }


}
